# -*-coding:utf-8-*-

from delegates.base import BaseDelegate
from daos.base_async import BaseRecord
from tornado.gen import coroutine, Return

SPECIFICS = {
    'user_id': 'USER_ID',
    'vendor_id': 'VENDOR_ID',  # 厂商，用于在用户端获取 product list
    'spreader_id': 'SPREADER_ID',  # 推广者
    'superior_spreader_id': 'SUPERIOR_SPREADER_ID',  # 上级推广者
    'top_spreader_id': 'TOP_SPREADER_ID',  # 顶级推广者
    'spread_level': 2,  # 推广级别，推广者级别+1

    'consumptions': {
        'bonus_points': 100,  # 消费积分
        'spread_bonus_points': 100,  # 在推广体系下的消费积分
        'amount': 100,  # 消费总金额
        'spread_amount': 100,  # 在推广体系下的消费总金额
    },

    'commissions': {
        'as_spreader': 100,  # 作为一级推广者所获取的提成
        'as_superior_spreader': 100,  # 作为二级推广者所获取的提成
        'as_top_spreader': 100,  # 作为三级推广者所获取的提成
    },

    # 'reward_last_calc_time': 100,
    # 'reward': 100,
}


# def get_spread_bonus_points(self):
#         spread_bonus_points = self._get_optional_field('spread_bonus_points')
#         if spread_bonus_points is None:
#             return 0
#         return spread_bonus_points
#
#     def get_spread_bonus_points_take_effect_time(self):
#         spread_bonus_points_take_effect_time = self._get_optional_field('spread_bonus_points_take_effect_time')
#         if spread_bonus_points_take_effect_time is None:
#             return 0
#         return spread_bonus_points_take_effect_time

class DgkUser(BaseRecord):
    def __getattr__(self, item):
        if 'spread_bonus_points' == item:
            args = ('consumptions', 'spread_bonus_points')
        else:
            args = (item,)
        return self._get_optional_field(*args)


class DgkUsersDelegate(BaseDelegate):
    def extract_info_from_spreader(self, spreader):
        output = dict()
        output['spreader_id'] = spreader.user_id
        if spreader.spreader_id is not None:
            output['superior_spreader_id'] = spreader.spreader_id
        if spreader.superior_spreader_id is not None:
            output['top_spreader_id'] = spreader.superior_spreader_id
        spread_level = spreader.spread_level
        if spread_level is not None:
            spread_level += 1
        else:
            spread_level = 1
        output['spread_level'] = spread_level
        if spreader.vendor_id is not None:
            output['vendor_id'] = spreader.vendor_id
        return output

    @coroutine
    def on_pre_create(self, **kwargs):
        target = 'user'
        if 'target' in kwargs:
            target = kwargs['target']
        specifics = kwargs['specifics']
        if 'member' == target:
            role_names = kwargs['role_names']
            exclusive_fields = []
            if 'vendor' in role_names:
                exclusive_fields.extend(['city', 'district'])
            elif 'agent_city' in role_names:
                exclusive_fields.append('district')
                # make sure 'cify' field exists
                self._extract_fields(specifics, required_fields=['city'])
            elif 'agent_district' in role_names or 'agent_district_partner' in role_names:
                # make sure 'cify' and 'district' fields exist
                self._extract_fields(specifics, required_fields=['city', 'district'])
            self._exclude_fields(specifics, exclusive_fields)
        elif 'user' == target:
            spreader_phone_no = specifics['spreader']
            user_specifics = yield self._get_user_specifics(phone_no=spreader_phone_no)
            if not user_specifics:
                self._respond_error(1, 'invalid user')
            spreader = DgkUser(user_specifics)
            spreader_role_names = yield self._get_user_role_names(phone_no=spreader_phone_no)
            if not set(spreader_role_names) & set(['vendor', 'agent_city', 'agent_district']):
                if not spreader.spread_bonus_points:
                    self._respond_error(2, 'normal user spread bonus points is 0')
            specifics = self.extract_info_from_spreader(spreader)
            # spreader_info = yield self._get_user_common_info(phone_no=spreader_phone_no)
            # specifics['spreader'] = spreader_info
            # specifics['spreader'] = spreader_phone_no
            if 'vendor' in spreader_role_names:
                specifics['vendor_id'] = spreader.user_id
        raise Return(specifics)

    @coroutine
    def on_post_get(self, **kwargs):
        specifics = kwargs['specifics']
        if 'spreader_id' in specifics:
            spreader_info = yield self._get_user_common_info(user_id=specifics['spreader_id'])
            specifics['spreader'] = spreader_info
        raise Return(specifics)

    @coroutine
    def on_pre_get_list(self, **kwargs):
        filter_cond = {}
        uid = self._uid
        aspect = kwargs['aspect'] if 'aspect' in kwargs else None
        if 'spread' == aspect:
            level = int(kwargs['level']) if 'level' in kwargs else 0
            if 0 == level:
                filter_cond = {'$or': [
                    {'specifics.spreader_id': uid},
                    {'specifics.superior_spreader_id': uid},
                    {'specifics.top_spreader_id': uid}
                ]}
            elif 1 == level:
                filter_cond = {'specifics.spreader_id': uid}
            elif 2 == level:
                filter_cond = {'specifics.superior_spreader_id': uid}
            elif 3 == level:
                filter_cond = {'specifics.top_spreader_id': uid}
        elif 'agent' == aspect:
            user_specifics = yield self._get_user_specifics()
            user = DgkUser(user_specifics)
            if 'roles' in kwargs:
                filter_cond.update(roles={'$in': kwargs['roles']})
            role_names = kwargs['role_names']
            if 'vendor' in role_names:
                filter_cond.update(superior_id=uid)
            if 'agent_city' in role_names:
                kwargs['city'] = user.city
            if 'agent_district' in role_names:
                kwargs['district'] = user.district

            if 'city' in kwargs:
                filter_cond.update({'specifics.city': kwargs['city']})
            if 'district' in kwargs:
                filter_cond.update({'specifics.district': kwargs['district']})
        else:
            filter_cond = {'superior_id': uid}
        raise Return((filter_cond, None))

    def on_pre_update(self, **kwargs):
        if 'role_names' not in kwargs:
            return None
        role_names = kwargs['role_names']
        specifics = kwargs['specifics']
        exclusive_fields = []
        if 'vendor' in role_names:
            exclusive_fields.extend(['city', 'district'])
        elif 'agent_city' in role_names:
            exclusive_fields.append('district')
            # make sure 'cify' field exists
            self._extract_fields(specifics, required_fields=['city'])
        elif 'agent_district' in role_names or 'agent_district_partner' in role_names:
            # make sure 'cify' and 'district' fields exist
            self._extract_fields(specifics, required_fields=['city', 'district'])
        self._exclude_fields(specifics, exclusive_fields)
        raise Return(specifics)
